package es.tid.jala.android.ejemplos;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import org.apache.http.util.ByteArrayBuffer;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.TextView;

public class HelloWebAndroid extends Activity {
	private String resultado;
	private TextView tv;
	private Handler handler;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// setContentView(R.layout.main);

		tv = new TextView(this);
		this.setContentView(tv);
		
		handler = new Handler();
		obtenerDatos.start();
	}

	private Runnable mostrarDatos = new Runnable() {
		public void run() {
			Log.d("HelloWebAndroid", "mostrarDatos...");
			tv.setText(resultado);
		}
	};
	
	private Thread obtenerDatos = new Thread() {
		public void run() {
			try {
				URL url = new URL("http://jair.lab.fi.uva.es/~joselop/hola.txt");
				URLConnection c = url.openConnection();

				InputStream is = c.getInputStream();
				BufferedInputStream bis = new BufferedInputStream(is);

				ByteArrayBuffer baf = new ByteArrayBuffer(50);
				int current = 0;
				while ((current = bis.read()) != -1) {
					baf.append((byte) current);
				}

				resultado = new String(baf.toByteArray());
			} catch (Exception e) {
				resultado = e.getMessage();
			}
			
			handler.post(mostrarDatos);
		}
	};
}